package server;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.net.Socket;
import java.net.SocketException;

import util.Logger;
import dataContracts.Command;

public class ClientConnection {
	String name;
	Socket socket;
	ObjectOutputStream objectWriter;
	ObjectInputStream objectReader;
	
	ClientConnection(Socket socket) throws IOException {
		this.socket = socket;
		objectWriter = new ObjectOutputStream(socket.getOutputStream());
		objectReader = new ObjectInputStream(socket.getInputStream());
	}
	
	public void notify(String message) {
		command(Command.Type.Broadcast, message);
	}
	
	public void command(Command.Type type, String message) {
		command(new Command(type, message));
	}
	
	public void command(Command cmd) {
		try {
			objectWriter.writeObject(cmd);
			objectWriter.flush();
			objectWriter.reset();
		} catch (SocketException e) {
			Logger.Warning("Dead socket still being used...");
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	public void closeConnection() {
		try {
			objectWriter.close();
			objectReader.close();
			socket.close();
		} catch (IOException e) {
			Logger.Warning("Client couldn't be closed correctly...");
		}
	}
}
